package cn.neusoft.service.impl;

import cn.neusoft.domain.Order1;
import cn.neusoft.domain.Task;
import cn.neusoft.enums.OrderStatus;
import cn.neusoft.enums.TaskState;
import cn.neusoft.exception.AppException;
import cn.neusoft.exception.AppExceptionCodeMsg;
import cn.neusoft.feignClients.DeliveryFeignClient;
import cn.neusoft.feignClients.OrderFeignClient;
import cn.neusoft.mapper.CommodityStatisticsMapper;
import cn.neusoft.query.BaseQuery;
import cn.neusoft.query.PaymentQuery;
import cn.neusoft.service.SubstationService;
import cn.neusoft.util.ExceptionUtils;
import cn.neusoft.vo.CommodityStatistics;
import cn.neusoft.vo.PageBean;
import cn.neusoft.vo.ResultBean;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class SubstationServiceImpl implements SubstationService {

    @Autowired
    DeliveryFeignClient deliveryFeignClient;

    @Autowired
    OrderFeignClient orderFeignClient;

    @Autowired
    CommodityStatisticsMapper commodityStatisticsMapper;

    /**
     * 分配任务
     *
     * @param task
     */
    @Transactional
    @Override
    public void assignTask(Task task) {

        ResultBean resultbean = deliveryFeignClient.findById(task.getTask_id());
        ExceptionUtils.throwOriginalException(resultbean);

        Task task1 = (Task) resultbean.getData();

        // 任务单状态不是可分配的
        if (!Objects.equals(task1.getTask_state(), TaskState.ASSIGNABLE.getCode())) {
            throw new AppException(AppExceptionCodeMsg.TASK_CANNOT_ASSIGN);
        }

        task1.setOperator_id(task.getOperator_id());
        task1.setTask_state(TaskState.ASSIGNED.getCode());

        // 通过openfeign调用调度中心修改任务单方法
        ResultBean resultBean1 = deliveryFeignClient.updateTask(task1);
        ExceptionUtils.throwOriginalException(resultBean1);

        // 修改订单状态
        Order1 order = new Order1();
        order.setOrder_id(task1.getOrder_id());
        order.setOrder_status(OrderStatus.ASSIGNED.getCode());
        ResultBean resultBean2 = orderFeignClient.updateOrderStatus(order);
        ExceptionUtils.throwOriginalException(resultBean2);
    }

    /**
     * 生成配送签收单
     *
     * @param task_id
     * @return
     */
    @Transactional
    @Override
    public Task generateDeliveryReceipt(String task_id) {

        ResultBean resultbean = deliveryFeignClient.findById(task_id);
        ExceptionUtils.throwOriginalException(resultbean);

        Task task = (Task) resultbean.getData();

        // 任务单状态不是已分配，不能生成配送签收单
        if (!Objects.equals(task.getTask_state(), TaskState.ASSIGNED.getCode())) {
            throw new AppException(AppExceptionCodeMsg.CANNOT_GENERATE_DELIVERY_RECEIPT);
        }

        task.calTotalPrice();

        return task;
    }

    /**
     * 回执录入
     */
    @Transactional
    @Override
    public void entryReceipt(Task task) {
        ResultBean resultbean = deliveryFeignClient.findById(task.getTask_id());
        ExceptionUtils.throwOriginalException(resultbean);

        Task task1 = (Task) resultbean.getData();

        // 任务单状态不是已领货
        if (!Objects.equals(task1.getTask_state(), TaskState.PICKED_UP.getCode())) {
            throw new AppException(AppExceptionCodeMsg.TASK_CANNOT_ENTRY_RECEIPT);
        }

        task1.setRemark(task.getRemark());
        task1.setTask_state(TaskState.FINISHED.getCode());

        // 任务单回执
        ResultBean resultBean1 = deliveryFeignClient.entryTask(task1);
        ExceptionUtils.throwOriginalException(resultBean1);

        // 修改订单状态
        Order1 order = new Order1();
        order.setOrder_id(task1.getOrder_id());
        order.setOrder_status(OrderStatus.FINISHED.getCode());
        ResultBean resultBean2 = orderFeignClient.updateOrderStatus(order);
        ExceptionUtils.throwOriginalException(resultBean2);
    }

    /**
     * 缴款查询
     *
     * @param query
     * @return
     */
    @Transactional
    @Override
    public PageBean inquiryPayment(PaymentQuery query) {

        // 计算分站小计
        Map<String, Object> subtotalMap = calSubTotal(query.getSubstation_id());

        // 构建结果对象
        PageBean<CommodityStatistics> pageBean = new PageBean<>();

        // 开启分页
        PageHelper.startPage(query.getPageNow(), query.getPageSize());

        // 分页查询结果对象
        List<CommodityStatistics> commodityStatisticsList = commodityStatisticsMapper.inquiryPayment(query);

        // 创建一个分页的实体PageInfo
        PageInfo<CommodityStatistics> pageInfo = new PageInfo<>(commodityStatisticsList);

        pageBean.setTotalRows(pageInfo.getTotal());
        pageBean.setTotalPages(pageInfo.getPages());
        pageBean.setRowData(pageInfo.getList());
        pageBean.setMap(subtotalMap);

        return pageBean;
    }

    @Transactional
    @Override
    public Map<String, Object> calSubTotal(Long substation_id) {

        PaymentQuery query = new PaymentQuery();
        query.setSubstation_id(substation_id);

        // 查询得到所有商品的缴款情况
        List<CommodityStatistics> list = commodityStatisticsMapper.inquiryPayment(query);

        BigDecimal totalReceiveMoney = BigDecimal.ZERO;
        BigDecimal totalReturnMoney = BigDecimal.ZERO;

        for (CommodityStatistics s : list) {
            totalReceiveMoney = totalReceiveMoney.add(s.getReceive_money());
            totalReturnMoney = totalReturnMoney.add(s.getReturn_money());
        }

        BigDecimal totalPayableMoney = totalReceiveMoney.subtract(totalReturnMoney);

        Map<String, Object> subtotalMap = new HashMap<>();
        subtotalMap.put("totalReceiveMoney", totalReceiveMoney);
        subtotalMap.put("totalReturnMoney", totalReturnMoney);
        subtotalMap.put("totalPayableMoney", totalPayableMoney);

        return subtotalMap;
    }
}
